#include"mac.h"
#include"ip.h"
#include"vlan.h"
#include"mpls.h"

FramHeader_t *mac_header;
char src_mac[MAC_LENGTH];
char des_mac[MAC_LENGTH];
char mac[MAC_LENGTH];

//用于填充mac-header中的字段
void init_mac(FILE *fp){
    mac_header = (FramHeader_t *)malloc(sizeof(FramHeader_t));
    memset(mac_header,0,sizeof(FramHeader_t));
    if (fread(mac_header, sizeof(FramHeader_t), 1, fp) != 1)
    {
        printf(" can not read mac_header\n");
    }
}


//mac转string
char *mac_to_str(u_int8 MAC[]){
    sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",
    MAC[0],MAC[1],MAC[2],MAC[3],MAC[4],MAC[5]);
    return mac;
}

// 源mac
char * get_src_mac(){
    strcpy(src_mac,mac_to_str(mac_header->SrcMAC));
    return src_mac;
}

//目的mac
char * get_des_mac(){
    strcpy(des_mac,mac_to_str(mac_header->DstMAC));
    return des_mac;
}

//获取协议类型
int get_frame_type(){
    return ntohs(mac_header->FrameType);
}

//释放mac_header内存
void free_mac(){
    free(mac_header);
}

void process_mac(FILE *fp){
    init_mac(fp);
    printf("src_mac:%s\t des_mac:%s\n",get_src_mac(),get_des_mac());

    switch (get_frame_type()){
        case FRAME_TYPE_IP:
            process_ip(fp);
            break;
        case FRAME_TYPE_VLAN:
            process_vlan(fp);
            break;
        case FRAME_TYPE_QinQ:
            process_vlan(fp);
            break;
        case FRAME_TYPE_MPLS:
            process_mpls(fp);
            break;
        default:
            printf("next part is not ip or vlan or QinQ or mpls\n");
            break;
    }

    free_mac();
}